import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';

import { Logger } from './utils/logger';
import { AppConfig } from './config/app.config';
import { HttpServer } from './utils/http';
import { registerServerRoutes } from './routes';
import { registerDesignDataTool } from './tools/design';
import { registerSwaggerDataTool } from './tools/swagger';

// https://swagger.mucang.cn/v3/index.html?url=https://volvo-coach.ttt.mucang.cn/__/swagger/view.htm#/volvo-coach.ttt.mucang.cn/%E6%95%99%E7%BB%83%E7%BA%BF%E7%B4%A2%E8%B4%AD%E4%B9%B0/d170045557ebfcc9ca606639b5c5f0eb

/*** 应用程序主入口点 */
async function main(): Promise<void> {
  let httpServer: HttpServer | null = null;

  let mcpServer: McpServer | null = null;

  try {
    Logger.info('🚀 启动应用程序...');

    // 加载配置
    const config = new AppConfig();

    httpServer = new HttpServer();

    // 启动服务器
    await httpServer.start(config);

    mcpServer = new McpServer({
      name: 'idoc-design-analysis-mcp',
      version: '1.0.0',
    });

    registerServerRoutes(mcpServer);

    registerDesignDataTool(mcpServer);

    registerSwaggerDataTool(mcpServer);

    Logger.info('✅ 应用程序启动完成');
  } catch (error) {
    Logger.error('❌ 应用程序启动失败:', error);
    process.exit(1);
  }

  // 监听关闭信号
  process.on('SIGTERM', () => {
    httpServer.stop();

    mcpServer.close();
  });

  process.on('SIGINT', () => {
    httpServer.stop();

    mcpServer.close();
  });
}

// 启动应用程序
main().catch(error => {
  Logger.error('💥 应用程序启动时发生未处理的错误:', error);
  process.exit(1);
});
